/**
 * 
 */
package com.gsit.misn.bilders;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.gsit.misn.common.MisnExcuter;
import com.gsit.misn.domain.Misn;
import com.gsit.misn.domain.Patient;
import com.gsit.misn.domain.User;
import com.gsit.misn.utils.ExcelReader;
import com.gsit.misn.utils.PatientUtil;
import com.gsit.misn.utils.Reader;
import com.thoughtworks.selenium.DefaultSelenium;

import static com.gsit.misn.utils.ScreenShotUtil.captureScreenShot;

/**
 * @author udichee
 *
 */
public class CreatePatientBilder implements PatientBilder <Misn> {

	
	
	private static Logger logger = LoggerFactory.getLogger(CreatePatientBilder.class);

	private Misn misn;
	private DefaultSelenium selenium;
	private Reader<User, List<Patient>> reader; 
	private Integer currNoOfRecords = 0;
	
	
	public void excute(DefaultSelenium selenium,final Misn misn ){
		this.misn = misn;
		this.selenium= selenium;
		if(MisnExcuter.CREATE_FROM_XLS == misn.getMisnExcuter()){
			createFromExcel();
		}
	}
	
	
	private void createFromExcel(){
		
		reader = new ExcelReader();
		List<Patient> patients = reader.read(misn.getUser());
		
		
		this.excuteCreatePage(patients);
		
	}
	
	public void excuteCreatePage(List<Patient> patients) {

		for (Patient patient : patients) {
			currNoOfRecords++;
			
			logger.info("currNoOfRecords "+currNoOfRecords+" :: "+patient.toString());
			
			System.out.println(patient.toString());
			
			if(!misn.getValidation()){
				createPageNavigation(selenium, patient);
			}
			
			
		}
		logger.info("Totla no of record are processed ..."+currNoOfRecords);
		

	}
	
	
	
	private void createPageNavigation(DefaultSelenium selenium, Patient patient) {
		
		System.out.println("The create page is "+misn.getMisnLinks().getCreateUrl());

		selenium.open(misn.getMisnLinks().getCreateUrl());
		selenium.waitForPageToLoad("10000");
		PatientUtil.setPatientIntoSelenium(selenium, patient,misn.getMisnExcuter().getType());		
		String button =misn.getMisnLinks().getCreateBtnName();
		String element = "//input[@value='"+button+"']";
		boolean isElm = selenium.isElementPresent(element);
		if(isElm){
			
			
			Date start = new Date(); 
			
			logger.info("Apply wait Start");
			try {
				Thread.sleep((misn.getUser().getWaitForProcess()*1000)+((Math.round((Math.random()*20)))*1000));
				// captureScreenShot screen 
				if(misn.getScreenShotCapture()){
					captureScreenShot(patient.getPatientID());
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Date end = new Date(); 
			logger.info("Apply wait End  : "+ (end.getTime()-start.getTime())/1000);
			
			selenium.click(element);
		}else{
			logger.error("No Add button found");
		}
		
		
		
		selenium.waitForPageToLoad("20000");

	}

	

}
